package edgeEntity

import (
	"encoding/json"
	"gitee.com/fierce_wolf/go-fox-edge-common/commEntity"
	"strconv"
)

type DeviceStatusEntity struct {
	BaseEntity *commEntity.BaseEntity // 基本信息

	CommSuccessTime int64 // 最近通信成功的时间，方便判定设备是否断连
	CommFailedTime  int64 // 最近访问失败的时间
	CommFailedCount int   // 连续访问失败的次数
}

type deviceStatusPo struct {
	Id              int64 `json:"id"`              // 对象id
	CreateTime      int64 `json:"createTime"`      // 创建时间
	UpdateTime      int64 `json:"updateTime"`      // 更新时间
	CommSuccessTime int64 `json:"commSuccessTime"` // 最近通信成功的时间，方便判定设备是否断连
	CommFailedTime  int64 `json:"commFailedTime"`  // 最近访问失败的时间
	CommFailedCount int   `json:"commFailedCount"` // 连续访问失败的次数
}

func (e *DeviceStatusEntity) Type() string {
	return "DeviceStatusEntity"
}

func (e *DeviceStatusEntity) TableName() string {
	return ""
}

func (e *DeviceStatusEntity) GetBaseEntity() *commEntity.BaseEntity {
	return e.BaseEntity
}

func (e *DeviceStatusEntity) Instance() *DeviceStatusEntity {
	return &DeviceStatusEntity{
		BaseEntity: new(commEntity.BaseEntity),
	}
}

func (e *DeviceStatusEntity) NewEntity() commEntity.IEntity {
	return e.Instance()
}

func (e *DeviceStatusEntity) NewPo() interface{} {
	return &deviceStatusPo{}
}

func (e *DeviceStatusEntity) MakeServiceKey() string {
	p := e.MakeServiceKeyList()
	return commEntity.MakeServiceKey(p)
}

func (e *DeviceStatusEntity) MakeServiceKeyList() []string {
	var p []string
	p = append(p, strconv.FormatInt(e.BaseEntity.Id, 10))
	return p
}

func (e *DeviceStatusEntity) BuildByJson(jsn *string) error {
	var po deviceStatusPo
	err := json.Unmarshal([]byte(*jsn), &po)
	if err != nil {
		return err
	}

	e.BuildByPo(&po)
	return nil
}

func (e *DeviceStatusEntity) BuildToJson() (string, error) {
	po := e.BuildToPo()
	code, err := json.Marshal(po)
	if err != nil {
		return "", err
	}

	return string(code), nil
}

func (e *DeviceStatusEntity) BuildByPo(pop interface{}) {
	ptr := e
	po := pop.(*deviceStatusPo)

	ptr.BaseEntity.Id = po.Id
	ptr.BaseEntity.CreateTime = po.CreateTime
	ptr.BaseEntity.UpdateTime = po.UpdateTime
	ptr.CommSuccessTime = po.CommSuccessTime
	ptr.CommFailedTime = po.CommFailedTime
	ptr.CommFailedCount = po.CommFailedCount
}

func (e *DeviceStatusEntity) BuildToPo() interface{} {
	ptr := e
	po := deviceStatusPo{}

	po.Id = ptr.BaseEntity.Id
	po.CreateTime = ptr.BaseEntity.CreateTime
	po.UpdateTime = ptr.BaseEntity.UpdateTime
	ptr.CommSuccessTime = po.CommSuccessTime
	ptr.CommFailedTime = po.CommFailedTime
	ptr.CommFailedCount = po.CommFailedCount

	return &po
}
